package com.apesay.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apesay.exception.ServiceException;
import com.apesay.service.base.ClientService;
import com.apesay.utils.Constant;
import com.apesay.utils.DataUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;

@RequiresAuthentication
public abstract class RestController {
	Logger logger = LoggerFactory.getLogger(RestController.class);
	protected abstract String getModel();

	@Resource
	private HttpSession session;
	@Autowired
	protected ClientService clientService;
	@RequiresAuthentication
	@RequestMapping("/delete/{id}")
	@ResponseBody
	public JSONObject delete(@PathVariable String id){
		JSONObject one = clientService.getObjectById(getModel(),id);
		one.put(Constant.DELSTATUS, 1);
		one.remove("msg");
		one.remove("data");
		one.remove("result");
		one.remove("status");
		return clientService.update(getModel(),id, one);
	}
	@RequiresAuthentication
	@RequestMapping("/remove/{id}")
	@ResponseBody
	public JSONObject remove(@PathVariable String id){
		return clientService.delete(getModel(),id);
	}
	@RequiresAuthentication
	@RequestMapping("/update/{id}")
	@ResponseBody
	public JSONObject update(@PathVariable String id,@RequestBody String body){
		return clientService.update(getModel(),id, JSON.parseObject(body));
	}
	@RequestMapping("/one/{id}")
	@ResponseBody
	public JSONObject get(@PathVariable String id){
		return clientService.getObjectById(getModel(),id);
	}
	@RequiresAuthentication
	@RequestMapping("/save")
	@ResponseBody
	public JSONObject save(@RequestBody String body){
		JSONObject one = JSON.parseObject(body);
		if (one.containsKey("signs")) {
			String signsStr = one.getString("signs");
			String[] signs = signsStr.split("/");
			for (String sign : signs) {
				JSONObject query = new JSONObject();
				query.put("sign", sign);
				JSONObject find = clientService.find(query.toJSONString(), "{}", "{}",Constant.model_sign, 0, 1);
				if (find.getJSONObject(Constant.RESULT).getIntValue("count")==0) {
					query.put("count", 1);
					clientService.add(Constant.model_sign,query);
				}else{
					JSONObject s = find.getJSONObject(Constant.RESULT).getJSONArray(Constant.RESULTS).getJSONObject(0);
					s.put("count", s.getIntValue("count")+1);
					clientService.update(Constant.model_sign,s.getString(Constant.OBJECTID), s);
				}
			}
		}
		return clientService.add(getModel(),JSON.parseObject(body));
	}
	@RequestMapping("/list")
	@ResponseBody
	public JSONObject list(@RequestBody String body) {
		try {
			if (DataUtils.isNotEmpty(body)) {
				JSONObject jsonObject=null;
				try{
					jsonObject = JSON.parseObject(body);
				}catch(Exception ex){
					//ignore
					String bd=URLDecoder.decode(body, "utf-8").replace("=", "");
					jsonObject=JSON.parseObject(bd);
				}
				JSONObject where=jsonObject.getJSONObject("query");
				if(where==null){
					where = new JSONObject();
				}
				return clientService.find(where.toJSONString(),
						jsonObject.getString("fields"),
						jsonObject.getString("orderby"),
						getModel(),
						jsonObject.getIntValue("skip"),
						jsonObject.getIntValue("size"));
			} else {
				return clientService.find("{}", "{}",
						"{}",getModel(), 0, 10);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			
			return new JSONObject();
		}
	}
	@RequestMapping("/page")
	@ResponseBody
	public JSONObject page(@RequestBody String body) {
		try {
			if (DataUtils.isNotEmpty(body)) {
				JSONObject jsonObject=null;
				try{
					jsonObject = JSON.parseObject(body);
				}catch(Exception ex){
					//ignore
					String bd=URLDecoder.decode(body, "utf-8").replace("=", "");
					jsonObject=JSON.parseObject(bd);
				}
				JSONObject where=jsonObject.getJSONObject("query");
				if(where==null){
					where = new JSONObject();
				}
				where.put(Constant.DELSTATUS, 0);
				return clientService.find(where.toJSONString(),
						jsonObject.getString("fields"),
						jsonObject.getString("orderby"),
						getModel(),
						jsonObject.getIntValue("skip"),
						jsonObject.getIntValue("size"));
			} else {
				return clientService.find("{}", "{}",
						"{}",getModel(), 0, 10);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			
			return new JSONObject();
		}
	}
	
	/**
	 * 获取系统当前登录用户
	 * 2015-10-29 13:13
	 * */
	public JSONObject getUser(){
		Object userObj = session.getAttribute("currentaccount");//当前登录用户
		JSONObject user = JSON.parseObject(userObj.toString());
		return user;
	}
	
	/**
	 * 添加日志公共方法
	 * @param operaId 操作记录的id
	 * @param description 操作内容
	 * @param action 操作类型：0增，1删，2改
	 * 2015-11-16 13:56
	 * */
	public void addLog(String operaId,int action,String description){
		//添加操作日志,表：SystemOperationLog
		JSONObject log = new JSONObject();
		log.put("userId", getUser().getString(Constant.OBJECTID));
		log.put("realname", getUser().getString("realname"));
		log.put("recordId", operaId);
		log.put("model", getModel());
		log.put("domain", "backend");
		log.put("action", action);//0增，1删，2改
		log.put("description", description);
		try {
			clientService.add(Constant.model_syslog,log);
		} catch (ServiceException e) {
			e.printStackTrace();
		}
	}
}
